package net.xdclass.listener;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.config.RabbitMQConfig;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.enums.EventMessageType;
import net.xdclass.exception.BizException;
import net.xdclass.model.EventMessage;
import net.xdclass.service.ShortLinkService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;


/**
 * @author admin
 */
@Component
@Slf4j
@RabbitListener(queues = RabbitMQConfig.shortLinkAddLinkQueue)
public class ShortLinkAddLinkMQListener {


	@Resource
	private ShortLinkService shortLinkService;


	@RabbitHandler
	public void shortLinkHandler(EventMessage eventMessage, Message message, Channel channel) throws IOException {
		log.info("监听到消息ShortLinkAddLinkMQListener message消息内容:{}", message);
		long tag = message.getMessageProperties().getDeliveryTag();
		try {
			eventMessage.setEventMessageType(EventMessageType.SHORT_LINK_ADD_LINK.name());
			shortLinkService.handlerAddShortLink(eventMessage);

		} catch (Exception e) {
			//处理业务异常，还有进行其他操作，比如记录失败原因
			log.error("消费失败:{}", eventMessage.toString());
			throw new BizException(BizCodeEnum.MQ_CONSUME_EXCEPTION);
		} finally {
		}
		log.info("消费成功:{}", eventMessage);
		//确认消息消费成功
		channel.basicAck(tag, false);

	}


}
